package com.example.common.aware;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationContextException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * @author zty
 * @apiNote
 * @project_name mybatis-demo
 * @user tain
 * @create_at 2023/6/23 9:58
 * @create_vio IntelliJ IDEA
 */
//@Lazy
@Component
public class MyApplicationContextAware implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    private MyApplicationContextAware() {
    }

    /**
     * SpringApplication 启动后 是否通过此方法设置上下文?
     */
    @Override
    public final void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        MyApplicationContextAware.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        if (applicationContext == null) {
            throw new ApplicationContextException("上下文环境为空！");
        }
        return applicationContext;
    }

    public static Object getBean(String beanName) {
        return getApplicationContext().getBean(beanName);
    }

    public static HttpServletRequest getHttpServletRequest() {
        return getServletRequestAttributes().getRequest();
    }

    private static ServletRequestAttributes getServletRequestAttributes() throws IllegalStateException {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new IllegalStateException("servletRequestAttributes is null!");
        }
        return attributes;
    }

    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    public static HttpSession getSession() {
        return getHttpServletRequest().getSession();
    }

    public static HttpServletResponse getHttpServletResponse() throws IllegalStateException {
        HttpServletResponse response = getServletRequestAttributes().getResponse();
        if (response == null){
            throw new IllegalStateException("httpServletResponse is null!");
        }
        return response;
    }
}
